package htmodels

import (
	"github.com/astaxie/beego/orm"
	"datapro/models"
)

func HTUserAdd(user *models.User) error {
	o := orm.NewOrm()
	_, err := o.Insert(user)
	return err
}

func HTUserGetDetail(user *models.User) error {
	o := orm.NewOrm()
	return o.Read(user)
}

func HTUserGetCount(search string, searchFiled string, UserType int) (int64, error) {
	o := orm.NewOrm()
	m := models.User{}
	count, err := o.QueryTable(m.TableName()).Filter(m.FN_UserType(), UserType).Filter(searchFiled + "__icontains", search).Count()
	return count, err
}

func HTUserGetList(users *[]models.User, fields []string, UserType int, offset int64, limit int, search string, searchFiled string, orderby string) error {
	o := orm.NewOrm()
	m := models.User{}
	_, err := o.QueryTable(m.TableName()).Filter(m.FN_UserType(), UserType).Filter(searchFiled + "__icontains", search).OrderBy(orderby).Offset(offset).Limit(limit).All(users, fields...)
	return err
}

func HTUserDelete(Ids []int64) (int64, error) {
	o := orm.NewOrm()
	m := models.User{}
	count, err := o.QueryTable(m.TableName()).Filter("Id" + "__in", Ids).Delete()
	return count, err
}
func HTUserUpdate(user *models.User) error {
	o := orm.NewOrm()
	_, err := o.Update(user)
	return err
}

//return true if pass and name(phone) right
func HTCheckUserLogin(m *models.User, pass string) bool {
	o := orm.NewOrm()
	querybuilder := o.QueryTable(m.TableName())
	querybuilder = querybuilder.Filter(m.FN_UserName(), m.UserName)
	if err := querybuilder.One(m); err != nil {
		return false
	}
	if pass != m.PassWord {
		return false
	}
	return true
}

func HTGetNickNameById(id int) string {
	o := orm.NewOrm()
	user:=models.User{Id:id}
	if err:=o.Read(&user);err!=nil{
		return ""
	}else{
		return user.NickName
	}
}

func HTGetUserNameById(id int) string{
	o := orm.NewOrm()
	user:=models.User{Id:id}
	if err:=o.Read(&user);err!=nil{
		return ""
	}else{
		return user.UserName
	}
}